#!/usr/bin/env node

const log = console.log,
      fs = require('fs'),
      join = require('path').join,
      err = console.error;

const cmd = process.argv[2],
      src = process.argv[3],
      fileList = [],
      folder = 'sysFile';

//创建一个数组，将sysFile下的所有文件和文件夹作为对象填入数组，并按照时间顺序排列
addFileList(folder);
function addFileList(folder){
  let files = fs.readdirSync(folder);

  for(let i=0;i<files.length;i++){
    let file = join(folder,files[i]);
    let size = fs.statSync(file).size,
        createTime = fs.statSync(file).birthtime;
    if(fs.statSync(file).isFile()){
      fileList.push({"fileName":file,"size":size,"createTime":createTime});
      continue;
    }
    
    if(fs.statSync(file).isDirectory()){
      fileList.push({"fileName":file,"size":size,"createTime":createTime});
      addFileList(file);
    }
  }
}
//冒泡排序
/*function bubbleSort(arr){
  let len = arr.length;
  for(let i = 0;i<arr.length;i++){
    for(let j = 0;j<arr.length-1-i;j++){
      if(arr[j].createTime>arr[j+1].createTime){
        let temp = arr[j+1];
        arr[j+1]=arr[j];
        arr[j]=temp;
      }
    }
  }
}
bubbleSort(fileList);*/
fileList.sort((a,b)=>{
  return a.createTime-b.createTime;
})
  //因为fileList中的fileName保存的是文件的路径（方便之后的操作），所以要
  //重新创建fileName为只带有文件名的数组
let fileList2=[];
if(cmd == '-list'){
  for(let i = 0; i<fileList.length;i++){
    let fileName = getName(fileList[i].fileName);
    fileList2.push({"fileName":fileName,"size":fileList[i].size,"createTime":fileList[i].createTime});
  }
  log(JSON.stringify(fileList2)); 
}else if(cmd == '-show'){
  //判断sysFile下有没有所要的文件
  for (let i = 0;i<fileList.length;){
    let fileName = fileList[i].fileName;

    if(fileName == 'sysFile/'+src){
      try{
        fs.readFile(fileList[i].fileName,'utf8',(err,data) => {
          if(err){
            console.error(err.message);
            return;
          }
          log(data);
        })
      }catch(e){
        console.error(e.message);
      }
      break;
    }
    i++;
    if(i == fileList.length){log('该文件不存在')}
  }
}else if(cmd == '-del'){
  del(`${folder}/${src}`);
}
function del(src){
  if(fs.statSync(src).isFile()) {
    log(`${getName(src)}删除成功`);
    fs.unlinkSync(src);
    return;
  }

  if(fs.statSync(src).isDirectory()) deleteDir(src);

  function deleteDir(folder){
    let files = fs.readdirSync(folder);
    for(let i = 0;i<files.length;i++){
      let file = join(folder,files[i]);
      if(fs.statSync(file).isFile()){
        fs.unlinkSync(file);
        log(`${getName(file)}删除成功`);
        continue;
      }
      if(fs.statSync(file).isDirectory()) {
        deleteDir(file);
      }
    }
    log(`${getName(folder)}删除成功`);
    fs.rmdirSync(folder);
  }
}
function getName(file){
  let list = file.split('/');
 // let f = list[list.length-1];
  return list[list.length-1];
}
